﻿using System.Collections.Generic;
using System.Linq;
using Coleotrack.Core;
using Coleotrack.Data.Models;
using NHibernate;
using NHibernate.Linq;

namespace Coleotrack.Data
{
    public class Repository<T> : IRepository<T> where T:IEntity, IValidation
    {
        private readonly ISession session;

        protected Repository(ISession session)
        {
            this.session = session;
        }

        public T Find(int id)
        {
            return session.Linq<T>().Single(e => e.Id == id);
        }

        public IQueryable<T> All()
        {
            return session.Linq<T>().AsQueryable();
        }

        public int Count()
        {
            return session.Linq<T>().Count();
        }

        public IEnumerable<T> Select()
        {
            return session.Linq<T>();
        }

        public void Save(T entity)
        {
            session.SaveOrUpdate(entity);
            session.Flush();
        }

        public void Delete(T entity)
        {
            session.Delete(entity);
            session.Flush();
        }
    }
}
